<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <label for="">设备名称：</label>
            <el-input
                v-model="searchForm.facilityName"
                placeholder="请输入设备名称"
                style="width: 155px"
            />
        </div>
        <div class="filter-item">
            <label for="">资产编号：</label>
            <el-input
                v-model="searchForm.assetNumber"
                placeholder="请输入资产编号"
                style="width: 155px"
            />
        </div>
        <div class="filter-item">
            <label for="">时间：</label>
            <el-date-picker
                style="width: 260px"
                v-model="searchForm.dateTime"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :size="'default'"
                :shortcuts="shortcuts"
            />
        </div>
        <div class="filter-item">
            <el-button
                size="default"
                type="primary"
                @click="search"
            >查询</el-button>
            <el-button
                size="default"
                type="primary"
                @click="reset"
            >重置</el-button>
            <el-button
                size="default"
                type="success"
                @click="exportList"
            >导出</el-button>
            <!-- <el-button size="default" type="success" @click="updateTask"
                >更新任务</el-button
            > -->
        </div>
    </div>

    <el-table
        :data="tableData"
        :key="timeStap"
        style="width: 100%"
        :size="'small'"
        :border="false"
    >
        <el-table-column
            type="index"
            label="序号"
            width="55"
        />
        <el-table-column
            prop="equipName"
            label="设备名称"
        />
        <el-table-column
            prop="equipLocations"
            label="安装位置"
        />
        <el-table-column
            prop="specificationModel"
            label="设备型号"
            width="220"
        />
        <el-table-column
            prop="assetNumber"
            label="资产编号"
            width="120"
        />
        <el-table-column
            prop="upkeepDesc"
            label="保养内容"
            width="160"
        />
        <el-table-column
            prop="upkeepLevel"
            label="保养级别"
        />
        <el-table-column label="维修内容">
            <el-table-column
                prop="lube"
                label="润滑油、脂"
            />
            <el-table-column
                prop="sealingElement"
                label="密封件"
            />
            <el-table-column
                prop="other"
                label="其他"
            />
        </el-table-column>
        <el-table-column
            prop="upkeepTime"
            label="计划保养日期"
        />
        <el-table-column
            prop="upkeepTime"
            label="维修保养日期"
            width="100"
        />
        <el-table-column
            prop="upkeepUser"
            label="检修人"
        />
        <el-table-column
            prop="acceptanceUser"
            label="验收人"
        />
        <el-table-column
            fixed="right"
            label="现场图片"
            width="80"
        >
            <template #default="scope">
                <div
                    class="demo-image__preview"
                    style="height: 30px"
                >
                    <div
                        v-if="scope.row.imageIds"
                        style="
                            display: flex;
                            flex-direction: row;
                            align-items: center;
                        "
                    >
                        <el-image
                            style="height: 30px"
                            preview-teleported
                            :src="scope.row.imageUrlItem"
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            :teleported="true"
                            :preview-src-list="scope.row.imageUrlList"
                            fit="cover"
                        />
                        <!-- <span> ({{ scope.row.imageUrlList.length }})</span> -->
                    </div>
                    <p
                        v-else
                        style="line-height: 30px"
                    >
                        暂无图片{{ scope.row.imageUrlItem }}
                    </p>
                </div>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog
        v-model="recordListVisible"
        title="操作记录"
        width="1000"
    >
        <div class="filter">
            <div class="filter-item">
                <label for="">操作时间：</label>
                <el-date-picker
                    style="width: 240px"
                    v-model="recordTime"
                    type="daterange"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :size="'default'"
                    :shortcuts="shortcuts"
                />
            </div>
            <div class="filter-item">
                <el-button
                    size="default"
                    type="warning"
                    @click="searchRecord(currentRowRecord)"
                >查询</el-button>
            </div>
        </div>
        <el-table
            :data="recordList"
            style="width: 100%"
        >
            <el-table-column
                prop="operationType"
                label="操作类型"
            />
            <el-table-column
                prop="createTime"
                label="操作时间"
                width="160"
            />
            <el-table-column
                prop="comment"
                label="操作内容"
                width="560"
            />
            <el-table-column
                prop="operationRealname"
                label="操作人"
            />
        </el-table>
        <el-pagination
            v-model:current-page="recordPageNo"
            v-model:page-size="recordPageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalRecord"
            @size-change="handleSizeChangeRecord"
            @current-change="handleCurrentChangeRecord"
            class="paginationStyle"
        />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="recordListVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="adjustVisible"
        title="调整"
        width="600"
    >
        <el-form label-width="120">
            <el-form-item
                label="调整项："
                prop="name"
            >
                <el-select
                    v-model="adjustType"
                    placeholder=""
                    style="width: 200px"
                >
                    <el-option
                        v-for="item in adjustList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                label="巡检人员："
                prop="name"
                style="width: 450px"
                v-show="adjustType == '巡检人员'"
            >
                <el-radio-group v-model="inspectionType">
                    <el-radio label="当日值班班组">当日值班班组</el-radio>
                    <el-radio label="固定班组">固定班组</el-radio>
                    <el-radio label="固定人员">固定人员</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item
                label=""
                prop="inspectionUser"
                v-show="adjustType == '巡检人员'"
            >
                <el-select
                    v-model="inspectionUser"
                    :placeholder="`请选择${inspectionType}`"
                    style="width: 200px"
                >
                    <el-option
                        :label="item.label"
                        :value="item.value"
                        v-for="item in typeList"
                        :key="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                label="计划保养时间："
                prop="name"
                style="width: 450px"
                v-show="adjustType == '计划巡检时间'"
            >
                <el-date-picker
                    style="width: 200px"
                    v-model="adjustTime"
                    type="date"
                    :size="'default'"
                />
            </el-form-item>
            <el-form-item
                label="计划保养时间："
                prop="name"
                style="width: 450px"
                v-show="adjustType == '任务状态'"
            >
                <el-select
                    v-model="adjustStatus"
                    placeholder=""
                    style="width: 200px"
                >
                    <el-option
                        v-for="item in adjustStatusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="adjustVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="adjusConfirm"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="reportTaskVisible"
        title="填报"
        width="800"
    >
        <el-tabs
            :tab-position="'left'"
            style="height: 300px"
            class="demo-tabs"
            v-model="activeName"
            :key="activeName"
            @tab-change="handleClick"
        >
            <el-tab-pane
                style="white-space: wrap"
                v-for="item in reportTaskDataList"
                :key="item.eqId"
                :name="item.id"
            >
                <template #label>
                    <div class="reportLabel">
                        <p>{{ item.facilityName }}</p>
                        <p>{{ item.facilityLocations }}</p>
                        <p>{{ item.facilityNumber }}</p>
                    </div>
                </template>
                <div class="projectBox">
                    <p>巡检项目</p>
                    <ul>
                        <li
                            v-for="(value, key) in item.items"
                            :key="key"
                        >
                            <div
                                class="liItem"
                                style="flex: 1"
                            >{{ key }}</div>
                            <div
                                class="liItem"
                                style="width: 130px"
                            >
                                <el-radio-group
                                    style="width: 100%"
                                    v-model="item.items[key]"
                                    @change="(val) => (item.items[key] = val)"
                                >
                                    <el-radio
                                        label="正常"
                                        size="small"
                                    >正常</el-radio>
                                    <el-radio
                                        label="异常"
                                        size="small"
                                    >异常</el-radio>
                                </el-radio-group>
                            </div>
                        </li>
                    </ul>
                </div>
            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reportTaskVisible = false">取消</el-button>
                <el-button
                    type="warning"
                    @click="reportTaskConfirm"
                >
                    保存
                </el-button>
                <el-button
                    type="primary"
                    @click="reportTaskConfirm"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import equipmentHttp from "@/https/equipment.js";
import schedulingHttp from "@/https/scheduling.js";
import userHttp from "@/https/user.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { ElMessage } from "element-plus";
import moment from "moment";
import { onMounted, reactive, ref, watch } from "vue";
const nowTime = new Date().getTime();
const day = new Date().getDay();
const oneDayTime = 24 * 60 * 60 * 1000;
let searchForm = reactive({
    facilityName: "",
    assetNumber: "",
    status: "90",
    dateTime: [],
    pageNo: 1,
    pageSize: 10,
});
const depIdList = ref([
    { label: "全部", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const inspectionLevelList = ref([
    { label: "全部", value: "" },
    { label: "一级", value: "一级" },
    { label: "二级", value: "二级" },
    { label: "三级", value: "三级" },
]);
const statusList = ref([
    { label: "全部", value: "" },
    { label: "未开始", value: "0" },
    { label: "进行中", value: "10" },
    { label: "已完成", value: "100" },
]);
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;

const recordListVisible = ref(false);
const adjustVisible = ref(false);

const shortcuts = [
    {
        text: "本年",
        value: () => {
            return [
                moment().startOf("year"),
                moment().endOf("year"),
            ];
        },
    },
    {
        text: "本月",
        value: () => {
            return [
                moment().startOf("month"),
                moment().endOf("month"),
            ];
        },
    },
    {
        text: "下月",
        value: () => {
            return [
                moment().add(1, 'month').startOf("month"),
                moment().add(1, 'month').endOf("month"),
            ];
        },
    },
    {
        text: "本周",
        value: () => {
            return [
                moment().startOf("week"),
                moment().endOf("week"),
            ];
        },
    },
    {
        text: "下周",
        value: () => {
            return [
                moment().add(1, 'week').startOf("week"),
                moment().add(1, 'week').endOf("week"),
            ];
        },
    },
    {
        text: "本日",
        value: () => {
            return [
                moment(),
                moment(),
            ];
        },
    },
];
let ruleForm = reactive({
    region: "",
    name: "",
    desc: "",
    continuous: "",
    value1: [],
    type11: "class",
    number: 1,
    dayNumber: 1,
    monthNumber: 1,
    weekNumber: "1",
    week: "Mon",
    inspectionType: 1,
});
const tableData = ref([]);
const adjustType = ref("巡检人员");
const inspectionType = ref("当日值班班组");
const inspectionUser = ref("");
const typeList = ref([]);
const adjustTime = ref(moment().format("YYYY-MM-DD"));
const adjustStatus = ref("100");

const classesShowList = ref([]);
// 查询班次信息
const getWorkClassQueryWorkClassShow = async (row) => {
    let params = {
        depId: row.depId,
        classType: "1",
        isDelete: "0",
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await schedulingHttp.workClassQueryWorkClass(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.className;
            item.shortLabel = item.classShortName + "";
            item.value = item.id + "";
            item.statusTrigger = false;
        });
        classesShowList.value = res.data.data.records;
        typeList.value = classesShowList.value;
    }
};
const userList = ref([]);
const userQueryUserList = async (row) => {
    let params = {
        depId: row.depId,
        isDelete: 0,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await userHttp.userQueryUserList(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.realName;
            item.value = item.id + "";
        });
        userList.value = res.data.data.records;
    }
};
const groupList = ref([]);
// 查询班组信息
const getWorkteamsQueryWorkTeams = async (row) => {
    let params = {
        depId: row.depId,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await schedulingHttp.workteamsQueryWorkTeams(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.teamName;
            item.value = item.id;
        });
        groupList.value = res.data.data.records;
    }
};
watch(
    inspectionType,
    (val) => {
        if (val == "当日值班班组") {
            typeList.value = classesShowList.value;
        } else if (val == "固定班组") {
            typeList.value = groupList.value;
        } else if (val == "固定人员") {
            typeList.value = userList.value;
        }
    },
    { deep: true }
);
const adjustStatusList = ref([
    { label: "未开始", value: "0" },
    { label: "进行中", value: "10" },
    { label: "已完成", value: "100" },
]);
const adjustList = ref([
    { label: "巡检人员", value: "巡检人员" },
    { label: "计划巡检时间", value: "计划巡检时间" },
    { label: "任务状态", value: "任务状态" },
]);
const currentAdjustRow = ref();
const optionAdjust = (row) => {
    getWorkClassQueryWorkClassShow(row);
    getWorkteamsQueryWorkTeams(row);
    userQueryUserList(row);
    adjustVisible.value = true;
    adjustType.value = "巡检人员";
    inspectionType.value = "当日值班班组";
    adjustTime.value = moment().format("YYYY-MM-DD");
    adjustStatus.value = "100";
    currentAdjustRow.value = row;
};
const adjusConfirm = async () => {
    let params = {
        id: "",
        inspPlanDate: "",
        operateUser: "",
        status: "",
        userMode: "",
    };
    params.id = currentAdjustRow.value.id;
    if (adjustType.value == "巡检人员") {
        params.inspPlanDate = "";
        params.status = "";
        params.userMode = inspectionType.value;
        if (inspectionUser.value) {
            params.operateUser = inspectionUser.value;
        } else {
            ElMessage({
                type: "error",
                message: `请选择${params.userMode}`,
            });
            return;
        }
    }
    if (adjustType.value == "计划巡检时间") {
        params.inspPlanDate = moment(adjustTime.value).format("YYYY-MM-DD");
        params.status = "";
        params.userMode = "";
        params.operateUser = "";
    }
    if (adjustType.value == "任务状态") {
        params.inspPlanDate = "";
        params.status = adjustStatus.value;
        params.userMode = "";
        params.operateUser = "";
    }
    const res = await schedulingHttp.inspTaskAdjustTask(params);
    console.log(res);
    if (res.data.code == 200) {
        ElMessage({
            type: "success",
            message: "调整成功",
        });
        search();
        adjustVisible.value = false;
    } else {
        ElMessage({
            type: "error",
            message: "调整失败",
        });
    }
};
const activeName = ref("");

const handleClick = (name) => {
    console.log(name);
};
const activeEq = ref({});
const currentTask = ref({});
// 填报
const reportTaskDataList = ref([]);
const reportTaskVisible = ref(false);
const reportTask = async (row) => {
    reportTaskVisible.value = true;
    currentTask.value = row;
    const res = await schedulingHttp.inspTaskQueryItems(row);
    if (res.data.code == "200") {
        console.log(res);
        res.data.data.forEach((item) => {
            let items = {};
            item.itemList.forEach((m) => {
                item.equipmentId = item.id;
                items[m] = "111";
            });
            item.items = items;
        });
        reportTaskDataList.value = res.data.data;
        activeName.value = res.data.data[0].id;
        activeEq.value = res.data.data[0];
    }
};
const reportTaskConfirm = async () => {
    let params = {
        id: currentTask.value.id,
        detailList: reportTaskDataList.value,
    };
    const res = await schedulingHttp.inspTaskReportTask(params);
    if (res.data.code == "200") {
        reportTaskVisible.value = false;
        ElMessage({
            type: "succsess",
            message: "填报成功",
        });
        search();
    } else {
        ElMessage({
            type: "error",
            message: "填报失败",
        });
    }
};

let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
const timeStap = ref(0);
const search = async () => {
    let params = {
        ...searchForm,
        startTime: searchForm.dateTime[0]
            ? moment(searchForm.dateTime[0]).format("YYYY-MM-DD")
            : "",
        endTime: searchForm.dateTime[1]
            ? moment(searchForm.dateTime[1]).format("YYYY-MM-DD")
            : "",
    };
    const res = await equipmentHttp.upkeepTaskQueryTask(params);
    console.log(res);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            if (item.items) {
                item.lube = item.items.lube;
                item.sealingElement = item.items.sealingElement;
                item.other = item.items.other;
                item.upkeepDesc = item.items.upkeepDesc;
            }
        });
        tableData.value = res.data.data.records;
        tableData.value.forEach((item) => {
            item.imageUrlItem = "";
            item.imageUrlList = [];
            if (item.imageIds != "") {
                equipmentHttp.fileInfoGetByIds(item.imageIds).then((result) => {
                    console.log(result, "result");
                    if (result.data.code == 200) {
                        item.imageUrlItem = result.data.data[0].url;
                        result.data.data.forEach((m) => {
                            item.imageUrlList.push(m.url);
                        });
                        timeStap.value++;

                        console.log(tableData.value, "tableData.value");
                    }
                });
            }
        });
        total.value = res.data.data.total;
    }
};

const exportList = () => {
    let params = {
        ...searchForm,
        startTime: searchForm.dateTime[0]
            ? moment(searchForm.dateTime[0]).format("YYYY-MM-DD")
            : "",
        endTime: searchForm.dateTime[1]
            ? moment(searchForm.dateTime[1]).format("YYYY-MM-DD")
            : "",
    };
    equipmentHttp.upkeepTaskExportUpkeep(params).then((response) => {
        console.log(response);
        const content = response.data;
        const blob = new Blob([content], { type: "application/ms-excel" });
        let fileName = `保养台账.xls`;
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
};
const reset = () => {
    searchForm.facilityName = "";
    searchForm.depId = localTypeUnit.value;
    searchForm.acceptanceStatus = "";
    searchForm.assetNumber = "";
    searchForm.dateTime = [];
    searchForm.pageNo = 1;
    searchForm.pageSize = 10;
    search();
};

const recordTime = ref([]);
const recordList = ref([]);
const currentRowRecord = ref();
const optionRecord = async (row) => {
    recordListVisible.value = true;
    currentRowRecord.value = row;
    recordTime.value[0] = moment().format("YYYY-MM-DD");
    recordTime.value[1] = moment().add(1, "day").format("YYYY-MM-DD");
    searchRecord(currentRowRecord.value);
};
const recordPageNo = ref(1);
const recordPageSize = ref(10);

let totalRecord = ref(0);
const handleSizeChangeRecord = (val) => {
    recordPageSize.value = val;
    searchRecord(currentRowRecord.value);
};
const handleCurrentChangeRecord = (val) => {
    recordPageNo.value = val;
    searchRecord(currentRowRecord.value);
};
const searchRecord = async (row) => {
    let params = {
        id: row.id,
        operationType: "",
        startTime:
            recordTime.value.length > 0
                ? moment(recordTime.value[0]).format("YYYY-MM-DD")
                : "",
        endTime:
            recordTime.value.length > 0
                ? moment(recordTime.value[1]).format("YYYY-MM-DD")
                : "",
        pageNo: recordPageNo.value,
        pageSize: recordPageSize.value,
    };
    const res = await schedulingHttp.operationRecordsQueryOperationRecords(
        params
    );
    console.log(res);
    if (res.data.code == 200) {
        recordList.value = res.data.data.records;
        totalRecord.value = res.data.data.total;
    }
};
const updateTask = () => { };
onMounted(() => {
    search();
});
</script>

<style scoped lang="less">
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}
.reportLabel {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 60px;
    p {
        line-height: 1.5;
    }
}
:deep .el-dialog__body {
    padding: 20px !important;
}
:deep .el-tabs__item {
    height: 70px !important;
}
.projectBox {
    padding: 0 20px;
    p {
        font-size: 16px;
        margin-bottom: 10px;
    }
    ul li {
        line-height: 1.5;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
}
</style>